import { reqLogout, reqUserCode, reqUserInfo, reqUserLogin, reqUserRegister } from "@/api"
import { getToken, clearToken, setToken } from "@/pages/utils/token"

const state={
    getCode:'',
    token:getToken(),
    userInfo:{}
}
const mutations={
    GETCODE(state,getCode){
        state.getCode=getCode
    },
    USERLOGIN(state,token){
        state.token=token
    },
   GETUSERINFO(state,userInfo){
        state.userInfo=userInfo
    },
    CLEAR(state){
        //清空仓库
        state.token='',
        state.userInfo={},
        //清空本地存储
        clearToken()
    }
}
const actions={
    //获取验证码
    async getCode({commit},phone){
        let result = await reqUserCode(phone)
        if(result.code==200){
            commit('GETCODE',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册---没有返回数据，不需要三连环存储
    async userRegister({commit},user){
        let result=await reqUserRegister(user)
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    //用户登录需要获取token
    async userLogin({commit},user){
    
        let result= await reqUserLogin(user)
        if(result.code==200){
            commit('USERLOGIN',result.data.token)
            //持久化存储
             setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message))
        }
        
    },
    //获取用户信息--登陆成功  在请求头添加用户token传递给服务器，此处不需再发
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        if(result.code==200){
            commit('GETUSERINFO',result.data)
            return "ok"
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    //退出登录
    async logout({commit}){
        //向服务器发起请求，通知清除token
        let result=await reqLogout()
        //action不能操作state,提交到mutations修改state
        if(result.code==200){
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters={}
export default{
    state,
    mutations,
    actions,
    getters
}